package controller.login;


import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import service.login.LoginService;
import util.encryption.Encryption;

@Controller
public class LoginController{
	
	 @Resource
     private LoginService loginService;
	 /**
	  * 登录
	  * @return
	  */
	 @RequestMapping(value="/login",method=RequestMethod.POST)
	 public String login(
			 RedirectAttributes redirectAttributes,
			 String name,
			 String password,
			 String code,
			 boolean rememberMe,
			 HttpServletRequest  req){
		 UsernamePasswordToken token = new UsernamePasswordToken(name,Encryption.MD5Encrypt(password));  
         Subject currentUser = SecurityUtils.getSubject(); 
		 try{
	             
	            //if (!currentUser.isAuthenticated()){
	                //使用shiro来验证
			/* token.setRememberMe(rememberMe); */
	                currentUser.login(token);//验证角色和权限 
	          //  } 
	             String verificationCode= req.getSession().getAttribute("verificationCode").toString();
	           	 if(verificationCode.equals(code)){
	           		 return "redirect:/jump/home";
	           	 }
	           	 if(!verificationCode.equals(code)){
	           		 redirectAttributes.addAttribute("message", "验证码错误");
	           		 return "redirect:/jump/index";
	           	 }
		 } catch (UnknownAccountException uae) {
			 redirectAttributes.addAttribute("message", token.getPrincipal()+"用户名不存在");
         } catch (IncorrectCredentialsException ice) {
        	 redirectAttributes.addAttribute("message", token.getPrincipal()+"密码错误");
         } catch (LockedAccountException lae) {
        	 redirectAttributes.addAttribute("message", "该用户已被锁定");
         }catch (AuthenticationException ae) {
        	 redirectAttributes.addAttribute("message", "未知错误，请联系管理员");
         }
    	 return "redirect:/jump/index";
     }
	 /**
	  * 退出
	  */
	 @RequestMapping(value="/logout",method=RequestMethod.GET)
	 public String logout(){
		 Subject currentUser = SecurityUtils.getSubject();
		 currentUser.logout();
		 return "redirect:/jump/index";
	 }
	 
	 
}
